package com.yazi.mxz.common.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.myframework.smhj.common.exception.MyException;
import com.myframework.smhj.common.exception.MyIllegalArgumentException;
import com.myframework.smhj.hibernate.dao.BasicService;
import com.myframework.smhj.hibernate.dao.Dao;
import com.yazi.mxz.common.MyUtil;
import com.yazi.mxz.common.db.dao.SecurityQuestionDao;
import com.yazi.mxz.common.entity.ValueFactory;
import com.yazi.mxz.common.entity.beans.Member;
import com.yazi.mxz.common.entity.beans.SecurityQuestion;
import com.yazi.mxz.common.service.SecurityQuestionService;

@Service("securityQuestionService")
public class SecurityQuestionServiceImpl extends BasicService<SecurityQuestion> implements SecurityQuestionService {
	
	private static Logger log = LoggerFactory.getLogger(SecurityQuestionServiceImpl.class);
	
	@Resource
	SecurityQuestionDao securityQuestionDao;

	@Override
	protected Dao<SecurityQuestion> getDao() {
		return securityQuestionDao;
	}
	
	@Override
	public List<SecurityQuestion> list(SecurityQuestion sq) {
		log.debug("search：");
		return securityQuestionDao.listByExample(sq);
	}

	@Override
	public void addByMember(Member member, List<SecurityQuestion> sqList) throws MyException {
		log.debug("addByMember：memberId={},size={}", member.getMemberId(), sqList.size());
		
		if (sqList.size() == 0) {
			throw new MyIllegalArgumentException("至少需要设置一个安全问答");
		}
		
		// 删除原有设置
		securityQuestionDao.delByMemberId(member.getMemberId());
		
		// 添加新设置
		for (SecurityQuestion sq : sqList) {
			ValueFactory.validate(sq);
			sq.setMember(member);
			sq.setAnswer(MyUtil.encodeSecurityAnswer(sq.getAnswer()));
			sq.setQuestionId(null);
			securityQuestionDao.persist(sq);
		}
	}

}
